<?php


namespace app\common\command\Db;


use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\Db;

class Recover extends Command
{
    protected function configure()
    {
        $this->setName('db:recover')
            ->addArgument('filename', Argument::REQUIRED, 'filename');
    }

    protected function execute(Input $input, Output $output)
    {
        $hostname = config('database.hostname');
        $database = config('database.database');
        $username = config('database.username');
        $password = config('database.password');
        $filename = MYSQL_BACKUP_PATH . $input->getArgument('filename');

        //mysqldump还原
        //$this->mysqldump($hostname, $database, $username, $password, $filename);

        //php原生还原
        $this->phprecover($hostname, $database, $username, $password, $filename);
    }

    protected function mysqldump($hostname, $database, $username, $password, $filename)
    {
        //数据恢复
        $command = sprintf('mysql -h%s -u%s -p%s %s < %s'
            , $hostname
            , $database
            , $username
            , $password
            , $filename
        );

        exec($command, $output, $status);
    }

    protected function phprecover($hostname, $database, $username, $password, $filename)
    {
        $sqls = explode(PHP_EOL . PHP_EOL, file_get_contents($filename));
        $sqls = array_filter($sqls);

        $connection = Db::getConnection();
        foreach ($sqls as $sql) {
            $PDOStatement = $connection->getPdo()->prepare($sql);
            $PDOStatement->execute();
            $PDOStatement->closeCursor();
        }
    }
}
